﻿using UnityEngine;
using System.Collections;

public class CharacterControllerScript : MonoBehaviour {
	
	public float movementSpeed = 5.0f;
	public float mouseSensitivity = 5.0f;
	public float jumpSpeed = 0.001f;
		
	CharacterController characterController;
	Vector3 velocity = Vector3.zero;

	
	// Use this for initialization
	void Start () {
		Screen.lockCursor = true;
		characterController = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {
		// Left-Right Rotation
		float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
		transform.Rotate(0, rotLeftRight, 0);

		// Up-Down Rotation (blocking if looking back)
		float verticalRotation = -Input.GetAxis("Mouse Y") * mouseSensitivity;
//		float newAngle = Camera.main.transform.rotation.eulerAngles.x + verticalRotation;
//		if(newAngle > 90 && newAngle < 280) {
//			verticalRotation = 0;
//		}
		Camera.main.transform.Rotate(verticalRotation,0,0);

		// Movement
		float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime;
		float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime;
		velocity = characterController.velocity;
		velocity[0] = sideSpeed;
		velocity[2] = forwardSpeed;

//		if (!isPhysicsGrounded()) {
//			velocity += Physics.gravity * Time.deltaTime;
//		} else {
//			for(int i = 0; i < 3;i++) {
//				if(Physics.gravity[i] != 0) {
//					velocity[i] = 0;
//					break;
//				}
//			}
//		}

//		if( characterController.isGrounded && Input.GetButtonDown("Jump") ) {
//			Vector3 jumpdir = Physics.gravity *-1f;
//			jumpdir = jumpdir.normalized * jumpSpeed;
//			velocity += jumpdir;
//		}


		velocity = transform.rotation * velocity;
		//Debug.Log (velocity);

		characterController.Move( velocity);
	}

//	private bool isPhysicsGrounded() {
//		if(Physics.gravity.y > 0) {
//			return (characterController.collisionFlags & CollisionFlags.Above) != 0;
//		} else {
//			return (characterController.collisionFlags & CollisionFlags.Below) != 0;
//		}
//	}
}
